package com.wdd.myplatform.controller;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.wdd.myplatform.utils.PdfUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * pdf生成下载
 * @author Administrator
 */
@RestController
@RequestMapping("/pdf")
public class PdfController {

    @GetMapping("/generate")
    public void generatePDF(HttpServletResponse response) throws Exception {
        String filename = "测试pdf";
        // 设置下载格式为pdf
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".pdf");
        OutputStream os = new BufferedOutputStream(response.getOutputStream());

        // 1. Document document = new Document();
        Document document = PdfUtil.createDocument();
        // 2. 获取writer
        PdfWriter.getInstance(document, os);
        // 3. open()
        document.open();

        //设置字体
        Font blackFont = PdfUtil.createFont(10, Font.NORMAL, BaseColor.BLACK);
        Font blueFont = PdfUtil.createFont(10, Font.NORMAL, BaseColor.BLUE);
        Font bigFont = PdfUtil.createFont(14, Font.NORMAL, BaseColor.BLACK);
        Font littleFont = PdfUtil.createFont(10, Font.NORMAL, BaseColor.BLACK);

        Paragraph title = PdfUtil.createParagraph("测试pdf", bigFont);
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);
        // 4. 添加段落内容
        document.add(PdfUtil.createParagraph("hello world",blackFont));
        document.add(PdfUtil.createParagraph("hello world2",blackFont));
        document.add(PdfUtil.createParagraph("hello world3",blackFont));
        document.add(PdfUtil.createParagraph("hello world4",blackFont));
        // 5. close()
        document.close();
        os.close();
    }
}
